import {LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED} from "../applications/app.helpers";

export async function toLoadPromise(app){
  if(app.loadPromise){ //确保在app.loadApp过程中不会重复调用app.loadApp
    return app.loadPromise;
  }

  return (app.loadPromise = Promise.resolve().then(async ()=>{
    app.status = LOADING_SOURCE_CODE;
    const {bootstrap, mount, unmount} = await app.loadApp(app.customProps);
    app.status = NOT_BOOTSTRAPPED;

    //可能是一个数组 就需要串行
    app.bootstrap = flattenArray(bootstrap);
    app.mount = flattenArray(mount);
    app.unmount = flattenArray(unmount);

    delete app.loadPromise;

    return app;
  }))
}


function flattenArray(fns){
  fns = Array.isArray(fns) ? fns : [fns];

  return (props) => fns.reduce((p, fn) => p.then(() => fn(props)), Promise.resolve());
}
